#include "socket.h"
#include "protocol.h"

string ops = "+-*/%&|^";

void thread_run(my_socket *clt)
{
    while (1)
    {
        // 1.读取服务端处理后的信息
        string buffer;
        string msg;
        clt->Recv(buffer, 100); // 将每一次序列化的数据都读进buffer里

        // 2.解包装
        Decode(buffer, msg);

        // 3.反序列化msg,
        Response rsp;
        rsp.Deserialize(msg);
        rsp.Info();

        sleep(3);
    }
}
int main(int argc, char *argv[])
{
    srand((unsigned int)time(nullptr));
    if (argc != 3)
    {
        cout << "格式错误\n正确格式:" << argv[0] << " ip"
             << " port" << endl;
    }
    string ip = argv[1];
    uint16_t port = atoi(argv[2]);

    my_socket *clt = new tcp_socket();
    clt->tcpclient_socket(ip, port); // 连接服务端套接字

    //创建线程专门负责接收信息
    thread reciver(thread_run,clt);
    reciver.detach();

    while (1)
    {
        int x = rand() % 100;
        int y = rand() % 100;
        char oper = ops[rand() % ops.size()];
        Request rq(x, y, oper);

        rq.info(); // 向客户端打印任务

        // 1.进行序列化并打包 发送数据
        string s;
        rq.Serialize(s);
        Encode(s);
        send(clt->Get_sockfd(), s.c_str(), s.size(), 0); // 任务发送给服务器

        sleep(1);
    }


    delete clt;
}